package com.magic.gre.ui.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.PagerSnapHelper;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.magic.gre.GREApp;
import com.magic.gre.R;
import com.magic.gre.adapter.WordsDetailsAdapter;
import com.magic.gre.base.activity.BaseMVPActivity;
import com.magic.gre.entity.WordsDetailsBean;
import com.magic.gre.helper.Apphelper;
import com.magic.gre.helper.Contract;
import com.magic.gre.mvp.contract.WordsDetailsContract;
import com.magic.gre.mvp.presenter.WordsDetailspresenterImpl;
import com.magic.gre.recording.AudioPlayManager;
import com.magic.gre.recording.IAudioPlayListener;
import com.magic.gre.ui.dialog.LearnFinishDialog;
import com.magic.gre.ui.popupwindow.VoicePopup;
import com.magic.gre.utils.PermissonUtils;
import com.noname.lib_base_java.entity.MsgEvent;
import com.noname.lib_base_java.net.RxBus;
import com.noname.lib_base_java.util.L;
import com.noname.lib_base_java.util.ToastUtil;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.functions.Consumer;

/**
 * Author: Lmoumou
 * Date: 2019-01-08 11:52
 * 文件名: WordsDetailsActivity
 * 描述:
 */
public class WordsDetailsActivity extends BaseMVPActivity<WordsDetailspresenterImpl> implements WordsDetailsContract.View,
        WordsDetailsAdapter.OnItemClickListener {

    private static final String TAG = "WordsDetailsActivity";

    @BindView(R.id.mRecyclerView)
    RecyclerView mRecyclerView;
    @BindView(R.id.mProgressBar)
    ProgressBar mProgressBar;
    @BindView(R.id.mTextView2)
    TextView mTextView2;
    @BindView(R.id.mTextView)
    TextView mTextView;
    @BindView(R.id.new_words_tv)
    TextView newWordsTv;
    @BindView(R.id.unit_tv)
    TextView unitTv;
    @BindView(R.id.ripe_words_tv)
    TextView ripeWordsTv;
    @BindView(R.id.mView)
    View mView;
    @BindView(R.id.shadow_v)
    View shadowV;

    public static void startThis(Context context, String unitId, int position) {
        Intent intent = new Intent(context.getApplicationContext(), WordsDetailsActivity.class);
        intent.putExtra("unitId", unitId);
        intent.putExtra("position", position);
        context.startActivity(intent);
    }

    public static void startThis(Context context, String unitId, String unitName, String lastId) {
        Intent intent = new Intent(context.getApplicationContext(), WordsDetailsActivity.class);
        intent.putExtra("unitId", unitId);
        intent.putExtra("unitName", unitName);
        intent.putExtra("lastId", lastId);
        context.startActivity(intent);
    }

    private WordsDetailsAdapter adapter;
    private List<WordsDetailsBean> dataList = new ArrayList<>();
    private String unitId;
    private String unitName;
    private WordsDetailsBean currentBean;
    private RxPermissions rxPermissions;
    private AnimationDrawable animation;
    private LinearLayoutManager layoutManager;
    @SuppressLint("UseSparseArrays")
    private Map<Integer, AnimationDrawable> aniMap = new HashMap<>();
    private String learnId;
    private String lastId;
    private int newWordsPosition = 0;


    @Override
    protected int getLayoutId() {
        return R.layout.activity_words_details;
    }

    @Override
    protected WordsDetailspresenterImpl creatPresenter() {
        return new WordsDetailspresenterImpl(this);
    }

    @Override
    protected void netOverride() {

    }

    @Override
    protected void onResume() {
        super.onResume();
        mPresenter.pCreat();
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (learnId != null) {
            mPresenter.pLearnRecordUpdate(learnId);
        }

        RxBus.getInstance().post(new MsgEvent(MsgEvent.LEARN_HISTORY));
    }

    @SuppressLint("SetTextI18n")
    @Override
    protected void initView(@Nullable Bundle savedInstanceState) {
        super.initView(savedInstanceState);
        aniMap.clear();
        unitId = getIntent().getStringExtra("unitId");
        newWordsPosition=getIntent().getIntExtra("position",0);
        if (unitId.equals(Contract.NEW_WORDS_ID)) {
            unitName = "生词本";
            unitTv.setText(unitName);
        } else {
            unitName = getIntent().getStringExtra("unitName");
            unitTv.setText(unitName);
            lastId = getIntent().getStringExtra("lastId");
        }

        adapter = new WordsDetailsAdapter(this, dataList, aniMap);
        adapter.setOnItemClickListener(this);
        PagerSnapHelper pagerSnapHelper = new PagerSnapHelper() {
            @Override
            public int findTargetSnapPosition(RecyclerView.LayoutManager layoutManager, int velocityX, int velocityY) {
                int targetPos = super.findTargetSnapPosition(layoutManager, velocityX, velocityY);
                if (targetPos + 1 <= adapter.getItemCount()) {
                    if (!dataList.isEmpty()) {
                        handler.removeCallbacksAndMessages(null);
                        AudioPlayManager.getInstance().stopPlay();
                        currentBean = dataList.get(targetPos);
                        newWordsTv.setSelected(currentBean.isUnirpe());
                        ripeWordsTv.setSelected(currentBean.isCooked());
//                        int pro = (100 / adapter.getItemCount()) * (targetPos + 1);
                        mProgressBar.setProgress(targetPos + 1);
                        mTextView2.setText(String.valueOf(targetPos + 1));
                        mPresenter.pRecordSave(currentBean.getId(), unitId);

                        if (Apphelper.getVoice()) {
                            String dirPath = Environment.getExternalStorageDirectory() + File.separator + GREApp.getContext().getPackageName() + File.separator + "Download" + File.separator + currentBean.getThesaurusId();
                            playVoice(aniMap.get(targetPos), currentBean.getVoicePath(dirPath));
                        }
                    }
                } else {
                    LearnFinishDialog dialog = new LearnFinishDialog();
                    dialog.setOnLearnFinishlistener(new LearnFinishDialog.OnLearnFinishlistener() {
                        @Override
                        public void onNextClick() {
                            LearnFinishActivity.startThis(WordsDetailsActivity.this, unitId, unitName);
                            WordsDetailsActivity.this.finish();
                        }
                    });
                    dialog.showThis(getSupportFragmentManager(), LearnFinishDialog.class.getSimpleName(), adapter.getItemCount());
                }

                return targetPos;
            }
        };

        mRecyclerView.setOnFlingListener(null);
        pagerSnapHelper.attachToRecyclerView(mRecyclerView);
        mRecyclerView.setLayoutManager(layoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
        mRecyclerView.setAdapter(adapter);

//        mPresenter.pLastUnit(unitId);
        mPresenter.pUnitDetails(unitId);
    }

    @OnClick(value = {R.id.new_words_tv, R.id.ripe_words_tv, R.id.right_iv})
    protected void onClick(View view) {
        switch (view.getId()) {
            case R.id.new_words_tv:
                mPresenter.pNewWordsSave(currentBean.getId(), 0);
                break;
            case R.id.ripe_words_tv:
                mPresenter.pRipeWordsSave(currentBean.getId(), 0);
                break;
            case R.id.right_iv:
                VoicePopup popup = new VoicePopup(this);
                popup.setShadowView(shadowV);
                popup.showPopupWindow(mView);
                break;
        }
    }

    @SuppressLint("SetTextI18n")
    @Override
    public void vUnitDatails(List<WordsDetailsBean> wordsBeanList) {
        dataList.addAll(wordsBeanList);
        mProgressBar.setMax(dataList.size());
        adapter.notifyDataSetChanged();
        newWordsTv.setEnabled(!dataList.isEmpty());
        ripeWordsTv.setEnabled(!dataList.isEmpty());
        mProgressBar.setProgress(1);
        mTextView.setText("/" + adapter.getItemCount());
        mTextView2.setText("1");

        if (unitId.equals(Contract.NEW_WORDS_ID)){
            currentBean=wordsBeanList.get(newWordsPosition);
            mProgressBar.setProgress(newWordsPosition + 1);
            mTextView2.setText(String.valueOf(newWordsPosition + 1));
            layoutManager.scrollToPositionWithOffset(newWordsPosition, 0);
            newWordsTv.setSelected(currentBean.isUnirpe());
            ripeWordsTv.setSelected(currentBean.isCooked());
            mPresenter.pRecordSave(currentBean.getId(), unitId);
        }else {
            if (lastId == null || lastId.equals("null") || TextUtils.isEmpty(lastId)) {
                if (!wordsBeanList.isEmpty()) {
                    currentBean = dataList.get(0);
                    newWordsTv.setSelected(currentBean.isUnirpe());
                    ripeWordsTv.setSelected(currentBean.isCooked());
                    mPresenter.pRecordSave(currentBean.getId(), unitId);
                }
            } else {
                for (int i = 0; i < dataList.size(); i++) {
                    if (dataList.get(i).getId().equals(lastId)) {
                        currentBean = dataList.get(i);
                        mProgressBar.setProgress(i + 1);
                        mTextView2.setText(String.valueOf(i + 1));
                        layoutManager.scrollToPositionWithOffset(i, 0);
                        newWordsTv.setSelected(currentBean.isUnirpe());
                        ripeWordsTv.setSelected(currentBean.isCooked());
                        mPresenter.pRecordSave(currentBean.getId(), unitId);
                        break;
                    }
                }
            }
        }
//        layoutManager.scrollToPositionWithOffset(dataList.size() - 1, 0);
    }

    @Override
    public void vNewWordsSave(int position) {
        if (newWordsTv.isSelected()) {
            ToastUtil.getInstance().showNormal(this, "已移出生词本");
        } else {
            ToastUtil.getInstance().showNormal(this, "已加入生词本");
        }

        if (!newWordsTv.isSelected()) {
            ripeWordsTv.setSelected(false);
        }
        newWordsTv.setSelected(!newWordsTv.isSelected());
        currentBean.setUnirpe(newWordsTv.isSelected());
        currentBean.setCooked(!newWordsTv.isSelected());
        RxBus.getInstance().post(new MsgEvent(MsgEvent.NEW_WORDS_CHANGE));
    }

    @Override
    public void vRipeWordsSave(int position) {
        if (ripeWordsTv.isSelected()) {
            ToastUtil.getInstance().showNormal(this, "已移出熟词本");
        } else {
            ToastUtil.getInstance().showNormal(this, "已加入熟词本");
        }

        if (!ripeWordsTv.isSelected()) {
            newWordsTv.setSelected(false);
        }
        ripeWordsTv.setSelected(!ripeWordsTv.isSelected());
        currentBean.setCooked(ripeWordsTv.isSelected());
        currentBean.setUnirpe(!ripeWordsTv.isSelected());
        RxBus.getInstance().post(new MsgEvent(MsgEvent.RIPE_WORDS_CHANGE));
    }

    @Override
    public void vRecordSave() {
//        RxBus.getInstance().post(new MsgEvent(MsgEvent.LEARN_HISTORY));
    }

    @Override
    public void vCountToDay(String count) {

    }

    @Override
    public void vCreat(String id) {
        this.learnId = id;
    }

    @Override
    public void vLastUnit(String lastId) {
        for (int i = 0; i < dataList.size(); i++) {
            if (dataList.get(i).getId().equals(lastId)) {
                L.e(TAG, "position->" + i);
                currentBean = dataList.get(i);
//                int pro = (100 / adapter.getItemCount()) * (i + 1);
                mProgressBar.setProgress(i + 1);
                mTextView2.setText(String.valueOf(i + 1));
                layoutManager.scrollToPositionWithOffset(i, 0);
//                mPresenter.pRecordSave(currentBean.getId(), unitId);
                break;
            }
        }
    }

    @Override
    public void onVoice(AnimationDrawable animation, String voicePath, int position) {
        this.animation = animation;
//        aniMap.put(position, animation);
        if (position == 0 && Apphelper.getVoice() && currentBean != null) {
            String dirPath = Environment.getExternalStorageDirectory() + File.separator + GREApp.getContext().getPackageName() + File.separator + "Download" + File.separator + currentBean.getThesaurusId();
            playVoice(aniMap.get(0), currentBean.getVoicePath(dirPath));
        }
    }

    @SuppressLint("CheckResult")
    @Override
    public void onPlayVoice(final AnimationDrawable animation, final String voicePath) {
        this.animation = animation;
        playVoice(animation, voicePath);
    }

    private Handler handler = new Handler();

    /**
     * 延迟1秒播放音频
     *
     * @param animation
     * @param voicePath
     */
    @SuppressLint("CheckResult")
    private void playVoice(final AnimationDrawable animation, final String voicePath) {
        File file = new File(voicePath);
        if (!file.exists()) {
//            ToastUtil.getInstance().showNormal(this, "资源不存在");
            return;
        }
        if (rxPermissions == null) {
            rxPermissions = new RxPermissions(this);
        }
        rxPermissions.request(PermissonUtils.VOICE)
                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(Boolean aBoolean) throws Exception {
                        if (aBoolean) {
                            handler.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    if (voicePath == null) {
                                        return;
                                    }
//                                    L.e("WordsDetailsActivity", "voicePath->" + voicePath);
                                    AudioPlayManager.getInstance().stopPlay();
                                    Uri audioUri = Uri.parse(voicePath);
                                    AudioPlayManager.getInstance().startPlay(WordsDetailsActivity.this, audioUri, new IAudioPlayListener() {
                                        @Override
                                        public void onStart(Uri var1) {
                                            if (animation != null)
                                                animation.start();
                                            mRecyclerView.setNestedScrollingEnabled(false);
                                        }

                                        @Override
                                        public void onStop(Uri var1) {
                                            if (animation != null) {
                                                animation.stop();
                                                animation.selectDrawable(0);
                                                mRecyclerView.setNestedScrollingEnabled(true);
                                            }

                                        }

                                        @Override
                                        public void onComplete(Uri var1) {
                                            if (animation != null) {
                                                animation.stop();
                                                animation.selectDrawable(0);
                                                mRecyclerView.setNestedScrollingEnabled(true);
                                            }
                                        }
                                    });
                                }
                            }, 500);

                        }
                    }
                });

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        AudioPlayManager.getInstance().stopPlay();
    }

    @Override
    public void onDialogMiss() {

    }
}
